<?php
/**
 * Controller using for CRUD classes table
 *
 * @author Dat Nguyen <datnt@evolable.asia>
 */
class CourseController extends AppController {
	var $uses = array('Course');

	public function beforeFilter() {
		parent::beforeFilter();
		$this->CustomAuth->allow('index', 'view');
	}

	/**
	 * Action add course
	 */
	function add() {
		$address_flg = 1;
		$isAddSchedule = 0;
		$openDate = date('Y-m-d H:i:s');
		$closeDate = date('Y-m-d H:i:s');
		if ($this->RequestHandler->isPost() && $this->data) {
			if(isset($this->data['CourseDetail'])){
				if($this->data['CourseDetail']['isAddSchedule'] == 1){
					$this->loadModel('CourseDetail');
					$this->_prepareCourseDetailData($this->data['CourseDetail']);
					$address_flg = $this->data['CourseDetail']['address_flg'];
					$openDate = $this->data['CourseDetail']['opening_date'];
					$closeDate = $this->data['CourseDetail']['closing_date'];
					$this->CourseDetail->set($this->data);
					$isAddSchedule = 1;
				}else{
					unset($this->data['CourseDetail']);
				}
				
			}
			$this->Course->set($this->data);
			if ($this->Course->validates()
				&& $this->Course->processImage() ) {
				if(isset($this->data['CourseDetail'])){
					if($this->CourseDetail->validateCourseDetail()){
						$this->_prepareConfirmData();
						$this->Session->write('courseForm', $this->Course->data);
						$this->redirect(array('controller' => 'course', 'action' => 'confirm'));
					}
				}else{
					$this->_prepareConfirmData();

					$this->Session->write('courseForm', $this->Course->data);

					$this->redirect(array('controller' => 'course', 'action' => 'confirm'));
				}
				
			}
		}
		$this->data['Course']['course_type'] = 1;
		$this->loadModel('Category');
		$this->loadModel('CourseType');
		$this->loadModel('Area');
		$this->set(array(
			'courseTypes' => $this->CourseType->find('all'),
			'categories' => $this->Category->find('list'),
			'areas' => $this->Area->find('list'),
			'address_flg' => $address_flg,
			'openDate' => $openDate,
			'closeDate' => $closeDate,
			'isAddSchedule' => $isAddSchedule
		));
	}

	/**
	 * Prepare data for confirm form
	 *
	 * @params $course Default course value
	 */
	function _prepareConfirmData($course = array()) {
		$this->loadModel('TempImage');
		if (isset ($this->Course->data['Course']['course_image01'])
			&& $image = $this->Course->data['Course']['course_image01']) {
			$temp = array(
				'id' => null,
				'image_path' => $image,
			);
			$data = $this->TempImage->save($temp);
			$data['TempImage']['id'] = $this->TempImage->id;
			$this->Course->data['Course']['course_image01'] = $data;
		} elseif (isset($course['Course']['course_image01'])
			&& $image = $course['Course']['course_image01']) {
			$data['TempImage'] =  array(
				'id' => null,
				'image_path' => $image,
			);;
			$this->Course->data['Course']['course_image01'] = $data;
		}

		if (isset ($this->Course->data['Course']['course_image02'])
			&& $image = $this->Course->data['Course']['course_image02']) {
			$temp = array(
				'id' => null,
				'image_path' => $image,
			);
			$data = $this->TempImage->save($temp);
			$data['TempImage']['id'] = $this->TempImage->id;
			$this->Course->data['Course']['course_image02'] = $data;
		} elseif ((!isset ($this->data['Course']['delete_image02']) || !$this->data['Course']['delete_image02'])
			&& isset($course['Course']['course_image02'])
			&& $image = $course['Course']['course_image02']) {
			$data['TempImage'] =  array(
				'id' => null,
				'image_path' => $image,
			);;
			$this->Course->data['Course']['course_image02'] = $data;
		}

		if (isset ($this->Course->data['Course']['course_image03'])
			&& $image = $this->Course->data['Course']['course_image03']) {
			$temp = array(
				'id' => null,
				'image_path' => $image,
			);
			$data = $this->TempImage->save($temp);
			$data['TempImage']['id'] = $this->TempImage->id;
			$this->Course->data['Course']['course_image03'] = $data;
		} elseif ((!isset ($this->data['Course']['delete_image03']) || !$this->data['Course']['delete_image03'])
			&& isset($course['Course']['course_image03'])
			&& $image = $course['Course']['course_image03']) {
			$data['TempImage'] =  array(
				'id' => null,
				'image_path' => $image,
			);;
			$this->Course->data['Course']['course_image03'] = $data;
		}
	}

	/**
	 * Confirm add course
	 */
	function confirm() {
		if ($this->RequestHandler->isPost() && $this->data) {
			$isEdit = false;
			if (isset ($this->data['Course']['id']) && $this->data['Course']['id']) {
				$course = $this->Course->getForEdit($this->data['Course']['id']);
				if (!$course) {
					$this->cakeError('error404');
				}

				if ($course['Course']['user_id'] != $this->CustomAuth->user('id')) {
					$this->Session->setFlash(Messages::error_you_isnt_the_author_of_this_course);
					$this->redirect(array('action' => 'index'));
				}
				$isEdit = true;
			} else {
				$course = array();
			}
			$imageIds = $this->_prepareSaveData($course);
			if ($newCourse = $this->Course->save($this->data)) {
				if ($imageIds) {
					$this->TempImage->deleteByIds($imageIds);
				}
				if ($isEdit) {
					if (isset ($this->data['Course']['course_image01'])
						&& $this->data['Course']['course_image01'] != $course['Course']['course_image01']) {
						$this->Course->removeOldImage($course['Course']['course_image01']);
					}

					if (isset ($this->data['Course']['course_image02'])
						&& $this->data['Course']['course_image02'] != $course['Course']['course_image02']) {
						$this->Course->removeOldImage($course['Course']['course_image02']);
					}
					if (isset ($this->data['Course']['course_image03'])
						&& $this->data['Course']['course_image03'] != $course['Course']['course_image03']) {
						$this->Course->removeOldImage($course['Course']['course_image03']);
					}

					$this->_sendEditEmail($this->data['Course']['id']);
				} else {
					$this->_updateUserStatus(true);
					if(isset($this->data['CourseDetail'])){// if add schedule when add course
						$this->_prepareSaveCourseDetail($this->Course->id);
						$this->loadModel('CourseDetail');
						try{
							$detail = $this->CourseDetail->save($this->data);
						}catch(Exception $ex){
						}
					}
					$this->_sendAddEmail($this->Course->id);
				}
				$this->redirect(array('action' => 'view', $this->Course->id));
			}
		}
		//check if have confirm data. If not redirect to add course page
		if (!$this->Session->check('courseForm')) {
			$this->redirect(array('controller' => 'course', 'action' => 'add'));
		}

		$this->data = $this->Session->read('courseForm');

		$this->_processConfirmData();

		$this->Session->delete('courseForm');
	}

	/**
	 * Process data before render confirm form
	 *
	 * @return array
	 */
	function _processConfirmData() {
		$course = $this->data;
		if (isset ($course['Course']['course_image01']['TempImage'])) {
			$this->data['Course']['course_image01'] = $course['Course']['course_image01']['TempImage']['id'];
			$course['Course']['course_image01'] = $course['Course']['course_image01']['TempImage']['image_path'];
		}
		if (isset ($course['Course']['course_image02']['TempImage'])) {
			$this->data['Course']['course_image02'] = $course['Course']['course_image02']['TempImage']['id'];
			$course['Course']['course_image02'] = $course['Course']['course_image02']['TempImage']['image_path'];
		}
		if (isset ($course['Course']['course_image03']['TempImage'])) {
			$this->data['Course']['course_image03'] = $course['Course']['course_image03']['TempImage']['id'];
			$course['Course']['course_image03'] = $course['Course']['course_image03']['TempImage']['image_path'];
		}

		$this->loadModel('Category');
		$this->loadModel('CourseType');
		$this->loadModel('Area');

		$area = $this->Area->getByCourse($course);
		$category = $this->Category->getByCourse($course);
		$type = $this->CourseType->getByCourse($course);
		if(isset($course['CourseDetail']) && count($course['CourseDetail']) > 0) {
			$areaCoureDetail = $this->Area->getById($course['CourseDetail']['area']);
			$this->set('areaCoureDetail', $areaCoureDetail);
		}
		$this->set(array(
			'course' => $course,
			'area' => $area,
			'category' => $category,
			'type' => $type,
		));
	}

	/**
	 * Prepare data for saving course
	 *
	 * @param $course
	 * @return array The list id of temporary images will be deleted when finish saving
	 */
	function _prepareSaveData($course = array()) {
		$imageIds = array(
			$this->data['Course']['course_image01'],
			$this->data['Course']['course_image02'],
			$this->data['Course']['course_image03'],
		);
		$this->loadModel('TempImage');
		$images = $this->TempImage->getListImages($imageIds);

		if (isset($images[$this->data['Course']['course_image01']])) {
			$this->data['Course']['course_image01'] = $images[$this->data['Course']['course_image01']];
		} else {
			$this->data['Course']['course_image01'] = $course['Course']['course_image01'];
		}

		if (isset($images[$this->data['Course']['course_image02']])) {
			$this->data['Course']['course_image02'] = $images[$this->data['Course']['course_image02']];
		}elseif (!isset($this->data['Course']['delete_image02'])) {
			$this->data['Course']['course_image02'] = $course['Course']['course_image02'];
		}

		if (isset($images[$this->data['Course']['course_image03']])) {
			$this->data['Course']['course_image03'] = $images[$this->data['Course']['course_image03']];
		}elseif (!isset($this->data['Course']['delete_image03'])) {
			$this->data['Course']['course_image03'] = $course['Course']['course_image03'];
		}

		$this->data['Course']['user_id'] = $this->CustomAuth->user('id');

		return $imageIds;
	}
	/**
	 * Action view course, with detail information
	 *
	 * @param null $id
	 */
	function view($id = null) {
		$userId = 0;
		if ($user = $this->CustomAuth->user()) {
			$userId = $user['User']['id'];
		} else {
			$this->Session->write('Auth.redirect', Router::url(array('controller' => $this->name, 'action' => $this->action, $id)));
		}
		if (!$this->Session->check('Admin.isLogin') || !$this->Session->read('Admin.isLogin')) {
			$options['conditions'] = array(
				$this->Course->alias . '.del_flg' => 0,
				'OR' => array(
					$this->Course->alias . '.display_flg' => 1,
					$this->Course->alias . '.user_id' => $userId,
				)
			);
		}
		$options['conditions'][$this->Course->alias . '.' . $this->Course->primaryKey] = $id;

		$course = $this->Course->getForView($options);

		if (!$course) {
			$this->cakeError('error404');
		}
		if (isset($this->params['url']['detail']) && $detailId = $this->params['url']['detail']) {
			$detail = $this->Course->getCourseDetail($id, $detailId);
		}
		if (!isset($detail) || !$detail) {
			$details = $this->Course->getClosestCourseDetail($id);
			$detail = array();
			if (isset($details[$id])) {
				$detail = $details[$id];
			}
		}
		$this->loadModel('CourseDetail');
		//check if joined to a course detail
		$this->loadModel('EnteredCourse');
		$this->loadModel('TargetOfWatch');
		$isJoined = false;
		$isFull = false;
		if ($detail) {
			$isJoined = $this->EnteredCourse->isEnteredCourse($detail['CourseDetail']['id'], $userId);
			$isFull = $this->CourseDetail->isFull($detail['CourseDetail']['id']);
		}

		$exclusiveIds = array($course['Course']['id']);

		$userCourses = $this->Course->getRelatedByUser($course['Course']['user_id'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($userCourses));
		$categoryCourses = $this->Course->getRelatedByCategory($course['Course']['category'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($categoryCourses));
		$areaCourses = $this->Course->getRelatedByArea($course['Course']['area'], $exclusiveIds);

		$this->loadModel('Tag');
		$watchListInfo = $this->TargetOfWatch->getTargetOfWatchInformationByUserIdAndTeacherId($this->CustomAuth->user('id'), $course['Course']['user_id']);
		$this->loadModel('Review');
		$options = array(
			'conditions' => array(
				$this->Review->alias . '.course_id' => $id,
				$this->Review->alias . '.del_flg' => 0,
			)
		);
		$this->set(array(
			'course' => $course,
			'detail' => $detail,
			'title_for_layout' =>  sprintf('「%s」の詳細', $course['Course']['title']),
			'areaCourses' => $areaCourses,
			'tags' => $this->Tag->getTagByCourse($id),
			'categoryCourses' => $categoryCourses,
			'userCourses' => $userCourses,
			'isJoined' => $isJoined,
			'isFull' => $isFull,
			'watchListInfo' => $watchListInfo,
			'reviews' => $this->Review->getList($options),
		));
	}

	function index($type = null, $id = null) {
		$this->helpers[] = 'Paginator';
		$options = $this->Course->getPaginatorOption();

		$this->loadModel('Area');
		$this->loadModel('Category');
		$this->loadModel('Tag');
		if (isset($type)) {
			$search = false;
			$searchText = '';
			switch ($type) {
				case 'category':
					$search = true;
					$options['conditions']['Course.category'] = $id;
					$category = $this->Category->read(null, $id);
					if (!$category) {
						$this->cakeError('error404');
					} else {
						$searchText = $category['Category']['name'];
					}
					break;
				case 'area':
					$search = true;
					$options['conditions']['Course.area'] = $id;
					$area = $this->Area->read(null, $id);
					if (!$area) {
						$this->cakeError('error404');
					} else {
						$searchText = $area['Area']['name'];
					}
					break;
				case 'time':
					$search = true;
					if ($id == 'now') {
						$options['conditions'][] = 'Course.id IN (SELECT cd.course_id FROM courses_detail cd WHERE cd.opening_date >= CURRENT_TIMESTAMP AND MONTH(cd.opening_date) = ' .date('m') .')';
						$searchText = 'this month';
					} elseif ($id == 'past') {
						$options['conditions'][] = 'Course.id IN (SELECT cd.course_id FROM courses_detail cd WHERE MONTH(cd.opening_date) < ' .date('m') .')';
						$searchText = 'upcoming';
					} else {
						$options['conditions'][] = 'Course.id IN (SELECT cd.course_id FROM courses_detail cd WHERE MONTH(cd.opening_date) > ' .date('m') .')';
						$searchText = 'previous';
					}
					break;
				case 'tag':
					$search = true;
					$tag = $this->Tag->read(null, $id);
					$options['conditions']['Course.id'] = array();
					if (!$tag) {
						$this->cakeError('error404');
					} else {
						$searchText = $tag['Tag']['name'];
					}
					$this->loadModel('Tagmap');
					$tags = $this->Tagmap->find('list', array(
						'fields' => array('id', 'course_id'),
						'conditions' => array('tag_id' => $id)
					));
					$options['conditions']['Course.id'] = $tags;
					break;
			}
			$this->set(array(
				'search' => $search,
				'type' => $type,
				'searchText' => $searchText,
				'searchId' => $id,
			));
		}
		if (isset ($this->params['url']['keyword']) && $keyword = $this->params['url']['keyword']) {
			$options['conditions']['OR']['Course.title LIKE'] = '%' . $keyword . '%';
			$options['conditions']['OR']['Course.description LIKE'] = '%' . $keyword . '%';
			$options['conditions']['OR']['Profile.first_name LIKE'] = '%' . $keyword . '%';
			$options['conditions']['OR']['Profile.last_name LIKE'] = '%' . $keyword . '%';
			$options['conditions']['OR']['Profile.description LIKE'] = '%' . $keyword . '%';
		}
		$this->paginate = $options;
		$courses = $this->paginate('Course');

		$ids = array();
		foreach ($courses as $course) {
			$ids[] = $course['Course']['id'];
		}
		$details = $this->Course->getClosestCourseDetail($ids);

		$this->set(array(
			'courses' => $courses,
			'details' => $details,
			'title_for_layout' => 'コース一覧 - Adams Campus',
			'categoryConfig' => Configure::read('category'),
		));
	}

	/**
	 * action enter a course
	 * @param null $id
	 */
	function enter($id = null) {
		$this->loadModel('EnteredCourse');
		$detailId = isset($this->params['url']['detail']) ? intval($this->params['url']['detail']) : 0;
		//if post, get post data
		if (isset($this->data['CourseDetail']['id'])) {
			$detailId = $this->data['CourseDetail']['id'];
		}
		$userId = $this->CustomAuth->user('id');
		$this->loadModel('CourseDetail');
		$isOwner = $this->CourseDetail->isOwner($detailId, $userId);
		$joined = $this->EnteredCourse->isEnteredCourse($detailId, $userId);
		$isFull = $this->CourseDetail->isFull($detailId);

		if ($this->RequestHandler->isPost()) {
			if (!$joined && !$isOwner && !$isFull) {
				$this->_processPayment();
			}
			return $this->cakeError('error404');
		}

		$course = $this->Course->getForEnter($id);

		$detail = $this->CourseDetail->getForEnter($detailId, $id);

		if (!$detail) {
			$this->cakeError('error404');
		}
		$this->set(array(
			'course' => $course,
			'detail' => $detail,
			'joined' => $joined,
			'isOwner' => $isOwner,
			'isFull' => $isFull,
			'backUrl' => $this->referer(),
		));
	}

	/**
	 * action pay success
	 * @param $id
	 */
	function paySuccess() {
		list($transaction, $result) = $this->_getPaymentDetail();
		if (isset($result['ACK']) && $result['ACK'] == 'Success') {
			//check amount money pay for course
			$userId = $transaction['Transaction']['user_id'];
			$detailId = $transaction['Transaction']['detail_id'];
			$this->loadModel('EnteredCourse');
			if ($result['AMT'] < $transaction['Transaction']['amount'] || $userId != $this->CustomAuth->user('id')) {
				$this->log('Error with payment amount, total money is less than course price. Paygate result: ' . json_encode($result), 'error');
				$this->cakeError('error500');
			} elseif ($this->EnteredCourse->isEnteredCourse($detailId, $userId)) {
				$this->log('User have enter course. Transaction detail ' . json_encode($transaction));
			} else {
				//process the last step in payment paypal process
				$params = array(
					'USER' => Configure::read('paypal.user'),
					'PWD' => Configure::read('paypal.password'),
					'SIGNATURE' => Configure::read('paypal.signature'),
					'VERSION' => 96.0,
					'METHOD' => 'DoExpressCheckoutPayment',
					'PAYERID' => $result['PAYERID'],
					'TOKEN' => $result['TOKEN'],
					'PAYMENTREQUEST_0_AMT' => $result['AMT'],
					'PAYMENTREQUEST_0_DESC' => $result['PAYMENTREQUEST_0_DESC'],
					'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
					'PAYMENTREQUEST_0_CURRENCYCODE' => Configure::read('currency_code'),
				);
				$socket = new HttpSocket();
				$response = $socket->get($this->endPoint, $params);
				parse_str($response, $result);
				//if get money successfully, save data to database
				if ($result['ACK'] == 'Success') {
					$transaction['Transaction']['status'] = 1;
					$transaction['Transaction']['extra_data'] = json_encode($result);
					$this->Transaction->save($transaction);

					$enteredCourse = array(
						'detail_id' => $detailId,
						'user_id' => $userId,
						'transaction_id' => $transaction['Transaction']['id'],
					);

					$this->EnteredCourse->save($enteredCourse);

					$this->loadModel('User');
					$this->User->addPoint($userId, $transaction['Transaction']['amount'], Configure::read('point_ratio'));
					$nowPoint = $this->User->getField('now_point', $userId);
					$this->CustomAuth->updateSessionData('now_point', $nowPoint);
					$this->_sendPaymentEmail($detailId, $userId);
				} else {
					$this->log('There is an error when process payment. Paygate response: ' . json_encode($result), 'error');
					$this->cakeError('error500');
				}
			}
		} else {
			$this->log('There is an error when get checkout result. Paygate response: ' . json_encode($result));
			$this->cakeError('error500');
		}
	}

	/**
	 * action pay cancel or failed
	 * @param $id
	 */
	function payFailed() {
		list($transaction, $result) = $this->_getPaymentDetail();
		$transaction['extra_data'] = json_encode($result);
		$this->Transaction->save($transaction);
	}

	/**
	 * Get payment detail, if success, get result for next step, if canceled, get result for update to database
	 *
	 * @return array
	 */
	function _getPaymentDetail() {
		$token = $this->params['url']['token'];

		$this->loadModel('Transaction');
		$transaction = $this->Transaction->getTransactionByToken($token);
		if (!$transaction) {
			$this->cakeError('error404');
		}
		Configure::load('paygate');
		$environment = Configure::read('paypal.environment');
		if('sandbox' === $environment || 'beta-sandbox' === $environment) {
			$this->endPoint = "https://api-3t.$environment.paypal.com/nvp";
		} else {
			$this->endPoint = 'https://api-3t.paypal.com/nvp';
		}
		$params = array(
			'USER' => Configure::read('paypal.user'),
			'PWD' => Configure::read('paypal.password'),
			'SIGNATURE' => Configure::read('paypal.signature'),
			'VERSION' => 96.0,
			'METHOD' => 'GetExpressCheckoutDetails',
			'TOKEN' => $token,
		);
		App::import('Core', 'HttpSocket');
		$socket = new HttpSocket();
		$response = $socket->get($this->endPoint, $params);
		parse_str($response, $result);
		return array($transaction, $result);
	}
	/**
	 * Process paypal payment
	 */
	function _processPayment() {
		if (isset($this->data['CourseDetail']['id']) && ($detailId = $this->data['CourseDetail']['id'])) {
			$this->loadModel('CourseDetail');
			$courseDetail = $this->CourseDetail->read(null, $detailId);
			if (!$courseDetail || strtotime($courseDetail['CourseDetail']['opening_date']) < time()) {
				$this->cakeError('error404');
			}

			Configure::load('paygate');
			//TODO: change paygate base the choosing of user
			$paymentId = 1;
			if (true) {
				App::import('Core', 'HttpSocket');
				$socket = new HttpSocket();
				$environment = Configure::read('paypal.environment');

				if("sandbox" === $environment || "beta-sandbox" === $environment) {
					$endPoint = "https://api-3t.$environment.paypal.com/nvp";
					$redirectUrl = "https://www.$environment.paypal.com/webscr?cmd=_express-checkout&token={TOKEN}";
				} else {
					$endPoint = 'https://api-3t.paypal.com/nvp';
					$redirectUrl = "https://www.paypal.com/webscr?cmd=_express-checkout&token={TOKEN}";
				}
				if (!($price = $courseDetail['CourseDetail']['price'])) {
					$price = $courseDetail['Course']['price'];
				}
				$params = array(
					'USER' => Configure::read('paypal.user'),
					'PWD' => Configure::read('paypal.password'),
					'SIGNATURE' => Configure::read('paypal.signature'),
					'VERSION' => 96.0,
					'METHOD' => 'SetExpressCheckout',
					'PAYMENTREQUEST_0_AMT' => $price,
					'PAYMENTREQUEST_0_DESC' => substr($courseDetail['Course']['title'], 0, 120),
					'L_PAYMENTREQUEST_0_NAME0' => substr($courseDetail['Course']['title'], 0, 120),
					'L_PAYMENTREQUEST_0_DESC0' => substr($courseDetail['Course']['description'], 0, 120),
					'L_PAYMENTREQUEST_0_AMT0' => $price,
					'L_PAYMENTREQUEST_0_QTY0' => 1,
					'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
					'PAYMENTREQUEST_0_CURRENCYCODE' => Configure::read('currency_code'),
					'returnUrl' => Router::url(array('full_base' => true, 'controller' => 'course', 'action' => 'paySuccess')),
					'cancelUrl' => Router::url(array('full_base' => true, 'controller' => 'course', 'action' => 'payFailed')),
				);
				$response = $socket->get($endPoint, $params);
				parse_str($response, $result);
				if (isset($result['ACK']) && $result['ACK'] == 'Success') {
					$this->loadModel('Transaction');
					$transaction = array(
						'detail_id' => $detailId,
						'user_id' => $this->CustomAuth->user('id'),
						'payment_id' => $paymentId,
						'amount' => $price,
						'status' => 0,
						'token' => $result['TOKEN'],
					);
					if ($this->Transaction->addTransaction($transaction)) {
						$redirectUrl = str_replace('{TOKEN}', urlencode($result['TOKEN']), $redirectUrl);
						$this->redirect($redirectUrl);
					} else {
						$this->log('Transaction could not save to database. Paygate result: ' . json_encode($result), 'error');
						$this->cakeError('error500');
					}
				} else {
					$this->log('Paygate error with following result: ' . json_encode($result), 'error');
					$this->cakeError('error500');
				}
			}
		}
	}

	/**
	 * Action for teacher hide his course
	 *
	 * @param $id
	 */
	function cancel($id = null) {
		$this->Course->recursive = -1;
		$course = $this->Course->read(array('id', 'user_id', 'title'), $id);

		if ($this->RequestHandler->isPost()) {
			$this->Course->recursive = -1;
			$course = $this->Course->read(array('id', 'user_id'), $id);

			if (!$course) {
				$this->cakeError('error404');
			}
			if ($course['Course']['user_id'] == $this->CustomAuth->user('id')) {
				$this->Course->updateDisplayFlg($id, 0);
				$this->Session->setFlash(Messages::course_change_successfully);
			} else {
				$this->Session->setFlash(Messages::error_you_isnt_the_author_of_this_course);
			}
			$this->redirect(array('action' => 'index'));
		}
		$this->set(array(
			'course' => $course,
			'id' => $id,
			'backUrl' => $this->referer(),
		));
	}

	/**
	 * Action for student leave a course he joined
	 *
	 * @param $id
	 */
	function leave($id = null) {
		$this->loadModel('CourseDetail');

		if ($this->RequestHandler->isPost()) {
			$this->loadModel('EnteredCourse');
			$detailId = $this->data['CourseDetail']['id'];
			$detail = $this->CourseDetail->getById($detailId);
			if (!$detail) {
				$this->cakeError('error404');
			}

			if ($this->CourseDetail->canLeave($detail)) {
				$userId = $this->CustomAuth->user('id');
				$this->EnteredCourse->leaveCourse($detailId, $userId);
				$this->loadModel('User');
				$this->User->removePoint($userId, $detail['CourseDetail']['price'], Configure::read('point_ratio'));
				//update point in session
				$nowPoint = $this->User->getField('now_point', $userId);
				$this->CustomAuth->updateSessionData('now_point', $nowPoint);
			}
			$courseId = $detail['CourseDetail']['course_id'];
			$this->_sendLeavingEmail($detail);
			$this->redirect(array('action' => 'view', $courseId));
		}
		$detailId = 0;
		if (isset($this->params['url']['detail'])) {
			$detailId = $this->params['url']['detail'];
		}
		$course = $this->Course->getForEnter($id);
		$detail = $this->CourseDetail->getForEnter($detailId, $id);
		if (!$detail || !$course) {
			$this->cakeError('error404');
		}
		$canLeave = $this->CourseDetail->canLeave($detail);

		$this->set(array(
			'course' => $course,
			'detail' => $detail,
			'canLeave' => $canLeave,
			'backUrl' => $this->referer(),
		));
	}

	function _sendLeavingEmail($detail) {
		$this->_initEmail();
		$this->loadModel('User');
		$user = $this->User->getById($this->CustomAuth->user('id'));

		//send email to site admin
		$this->Email->to = Configure::read('Course.leaving_notification_email');
		$this->Email->subject = Messages::leaving_email_site_subject;
		$this->Email->template = 'leaving_email_site';
		$this->set(array(
			'user' => $user,
			'detail' => $detail,
		));
		$this->Email->send();

		//send email to user
		$this->Email->to = $user['User']['email'];
		$this->Email->subject = Messages::leaving_email_user_subject;
		$this->Email->template = 'leaving_email_user';
		$this->Email->send();
	}

	/**
	 * Action for admin course page
	 */
	function admin_index() {
		$this->helpers[] = 'Paginator';
		if ($this->RequestHandler->isPost()) {
			if (isset($this->data['id'])) {
				switch ($this->data['type']) {
					case 'delete':
						$this->Course->updateDelFlg($this->data['id'], 1);
						break;
					case 'undelete':
						$this->Course->updateDelFlg($this->data['id'], 0);
						break;
					case 'authenticate':
						$this->Course->updateDisplayFlg($this->data['id'], 1);
						break;
					case 'notauthenticate':
						$this->Course->updateDisplayFlg($this->data['id'], 0);
						break;
					case 'recommend':
						$this->loadModel('RecommendCourse');
						$this->RecommendCourse->addRecommend($this->data['id']);
						break;
					case 'unrecommend':
						$this->loadModel('RecommendCourse');
						$this->RecommendCourse->removeRecommend($this->data['id']);
						break;
					default:
						$this->cakeError('error500');
				}
			}
			$this->Session->setFlash(Messages::update_successfully);
			$this->redirect($this->referer());
		}
		$options = $this->Course->getPaginatorOption();
		if (isset($this->params['url']['limit'])) {
			$options['limit'] = intval($this->params['url']['limit']);
		} else {
			$options['limit'] = 25;
		}

		if (isset($this->params['url']['sort']) && $this->params['url']['sort'] == 'oldest') {
			$this->passedArgs['direction'] = 'ASC';
		} else {
			$this->passedArgs['direction'] = 'DESC';
		}
		$this->passedArgs['sort'] = 'modified';
		$options['conditions'] = array();
		if (!isset($this->params['url']['del'])) {
			$options['conditions']['Course.del_flg'] = 0;
		} else {
			$options['conditions']['Course.del_flg'] = 1;
		}
		if (isset($this->params['url']['auth']) && $auth = $this->params['url']['auth']) {
			if (is_array($auth)) {
				$options['conditions']['Course.display_flg'] = $auth;
			} else {
				$options['conditions']['Course.display_flg'] = intval($auth);
			}
		} elseif (!isset($this->params['url']['del'])) {
			$options['conditions']['Course.display_flg'] = 0;
		}
		//recommend condition
		if (isset($this->params['url']['rec'])) {
			$options['conditions'][] = 'Course.id IN (SELECT rc.course_id FROM recommend_courses rc)';
		}
		$this->paginate = $options;
		$courses = $this->paginate('Course');
		$this->set(array(
			'courses' => $courses,
			'title_for_layout' => 'Manage Course'
		));
		$this->_getAdminStatistic();
	}

	/**
	 * Using for requestAction views, return the list of category, area, tag for search element
	 *
	 * @return array
	 */
	function getMasterData() {
		$this->loadModel('Area');
		$this->loadModel('Category');
		$this->loadModel('Tag');

		if (isset($this->params['requested'])) {
			return array(
				$this->Category->find('all', array('recursive' => '-1')),
				$this->Area->find('list'),
				$this->Tag->getTagsForFilter(),
			);
		} else {
			$this->cakeError('error404');
		}
	}

	/**
	 * Using for requestAction on views, return the new courses
	 * @return mixed
	 */
	function getNewCourse() {
		if (isset($this->params['requested'])) {
			$courses = $this->Course->getNewCourse(3);
			$ids = array();
			foreach ($courses as $course) {
				$ids[] = $course['Course']['id'];
			}
			$details = $this->Course->getClosestCourseDetail($ids);
			return array($courses, $details);
		} else {
			$this->cakeError('error404');
		}
	}

	/**
	 * Using for requestAction on views, return 1 special course
	 * @return mixed
	 */
	function getSpecialCourse() {
		if (isset($this->params['requested'])) {

		} else {
			return $this->cakeError('error404');
		}
	}

	/**
	 * Action for edit course
	 */
	function edit($id) {
		$course = $this->Course->getForEdit($id);
		if (!$course) {
			$this->cakeError('error404');
		}

		if ($course['Course']['user_id'] != $this->CustomAuth->user('id')) {
			$this->Session->setFlash(Messages::error_you_isnt_the_author_of_this_course);
			$this->redirect(array('action' => 'index'));
		}
		if (($this->RequestHandler->isPost() || $this->RequestHandler->isPut()) && $this->data) {
			$this->Course->set($this->data);
			if ($this->Course->validates()
				&& $this->Course->processImage()) {

				$this->_prepareConfirmData($course);

				$this->Session->write('courseForm', $this->Course->data);

				$this->redirect(array('controller' => 'course', 'action' => 'confirm'));
			}
		}
		$this->data = $course;
		$this->loadModel('Category');
		$this->loadModel('CourseType');
		$this->loadModel('Area');
		$this->set(array(
			'courseTypes' => $this->CourseType->find('all'),
			'categories' => $this->Category->find('list'),
			'areas' => $this->Area->find('list'),
		));
	}

	/**
	 * Send email to user attend to course when course update information
	 */
	function _sendEditEmail($courseId) {
		$this->loadModel('User');
		$users = $this->User->getUserJoinedCourse($courseId);
		$view = new View($this);
		$view->set('course', $this->data);
		$this->loadModel('QueueEmail');
		$this->loadModel('CourseDetail');
		$details = $this->CourseDetail->getForNotification($courseId);

		$userDetails = array();
		foreach ($details as $detail) {
			$userDetails[$detail['EnteredCourse']['user_id']] = $detail;
		}
		foreach ($users as $user) {
			$view->set(array(
				'user' => $user,
				'detail' => $userDetails[$user['User']['id']],
			));
			$content = $view->render('/elements/email/html/edit_course', '/email/html/default');
			$view->hasRendered = false;
			$to = array($user['User']['email']);
			$data = array(
				'id' => null,
				'subject' => Messages::change_course_information,
				'email_to' => json_encode($to),
				'content' => $content,
				'status' => 0,
				'created' => time(),
				'email_type' => QueueEmail::EMAIL_TYPE_COURSE,
			);
			$this->QueueEmail->save($data);
		}
	}

	/**
	 * Send add email to watching user
	 */
	function _sendAddEmail($courseId) {
		$this->loadModel('QueueEmail');
		$this->loadModel('User');
		$view = new View($this);
		$view->set(array(
			'courseId' => $courseId,
			'course' => $this->data,
		));
		$users = $this->User->getWatchList($this->CustomAuth->user('id'));
		foreach ($users as $user) {
			$view->set('user', $user);
			$content = $view->render('/elements/email/html/add_course', '/email/html/default');
			$view->hasRendered = false;
			$to = array($user['User']['email']);
			$data = array(
				'id' => null,
				'subject' => Messages::add_course_information,
				'email_to' => json_encode($to),
				'content' => $content,
				'status' => 0,
				'created' => time(),
				'email_type' => QueueEmail::EMAIL_TYPE_COURSE,
			);
			$this->QueueEmail->save($data);
		}
	}

	/**
	 * Send email when payment finish
	 */
	function _sendPaymentEmail($detailId, $joinUserId) {
		$this->loadModel('User');
		$this->loadModel('CourseDetail');
		$courseDetail = $this->CourseDetail->getById($detailId);
		if (!$courseDetail) {
			return;
		}
		$user = $this->User->getById($courseDetail['Course']['user_id']);
		$view = new View($this);
		$this->loadModel('QueueEmail');
		$view->set(array(
			'user' => $user,
			'courseDetail' => $courseDetail,
			'joinUserId' => $joinUserId,
		));
		//email to site
		$to = array(Configure::read('Notification.site_email'));
		$content = $view->render('/elements/email/html/enter_course_site', '/email/html/default');
		$view->hasRendered = false;
		$data = array(
			'id' => null,
			'subject' => Messages::enter_course_site,
			'email_to' => json_encode($to),
			'content' => $content,
			'status' => 0,
			'created' => time(),
			'email_type' => QueueEmail::EMAIL_TYPE_COURSE,
		);
		$this->QueueEmail->save($data);

		//email to  teacher
		$to = array($user['User']['email']);
		$content = $view->render('/elements/email/html/enter_course_owner', '/email/html/default');
		$view->hasRendered = false;
		$data = array(
			'id' => null,
			'subject' => Messages::enter_course_teacher,
			'email_to' => json_encode($to),
			'content' => $content,
			'status' => 0,
			'created' => time(),
			'email_type' => QueueEmail::EMAIL_TYPE_COURSE,
		);
		$this->QueueEmail->save($data);

		//email to  student
		$student = $this->User->getById($joinUserId);
		$to = array($student['User']['email']);
		$view->set(array(
			'user' => $student,
		));
		$content = $view->render('/elements/email/html/enter_course_student', '/email/html/default');
		$view->hasRendered = false;
		$data = array(
			'id' => null,
			'subject' => Messages::enter_course_student,
			'email_to' => json_encode($to),
			'content' => $content,
			'status' => 0,
			'created' => time(),
			'email_type' => QueueEmail::EMAIL_TYPE_COURSE,
		);
		$this->QueueEmail->save($data);
	}
	
	
	/**
	 * add string to opendate string, close date string
	 * @param array $form
	 */
	function _prepareCourseDetailData($courseDetail = array()) {
		$inputOpenDate = $courseDetail['year'].'-'.$courseDetail['month'].'-'.$courseDetail['day'].' '.$courseDetail['openHour']['hour'].':'.$courseDetail['openMinute']['min'].':00';
		$inputCloseDate = $courseDetail['year'].'-'.$courseDetail['month'].'-'.$courseDetail['day'].' '.$courseDetail['closeHour']['hour'].':'.$courseDetail['closeMinute']['min'].':00';
		$this->data['CourseDetail']['opening_date'] = date('Y-m-d H:i:s', strtotime($inputOpenDate));
		$this->data['CourseDetail']['closing_date'] = date('Y-m-d H:i:s', strtotime($inputCloseDate));
	}
	
	function _prepareSaveCourseDetail($courseid){
		if(isset($this->data['CourseDetail'])){
			$this->data['CourseDetail']['notice'] = htmlspecialchars($this->data['CourseDetail']['notice']);
			$this->data['CourseDetail']['address01'] = htmlspecialchars($this->data['CourseDetail']['address01']);
			$this->data['CourseDetail']['address02'] = htmlspecialchars($this->data['CourseDetail']['address02']);
			$this->data['CourseDetail']['place_name'] = htmlspecialchars($this->data['CourseDetail']['place_name']);
			$this->data['CourseDetail']['course_id'] = $courseid;
			$this->data['CourseDetail']['del_flg'] = 0;
			$this->data['CourseDetail']['payout_flg'] = 0 ;
		}
	}

	/**
	 * Get site statistic for admin
	 */
	function _getAdminStatistic() {
		$this->loadModel('Category');
		$categories = $this->Category->getCourseStatistic();
		$this->loadModel('Area');
		$areas = $this->Area->getCourseStatistic();
		$this->loadModel('User');
		$nbUser = $this->User->getTotalUser();
		$nbActiveUser = $this->User->getTotalActiveUser();
		$nbCourse = $this->Course->getTotalCourse();
		$this->set(array(
			'categories' => $categories,
			'areas' => $areas,
			'nbUser' => $nbUser,
			'nbActiveUser' => $nbActiveUser,
			'nbCourse' => $nbCourse,
		));
	}

	function admin_schedule() {

	}
}